package util;

import client.entity.Message;
import com.alibaba.fastjson.JSON;
import server.util.MyUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CacheUtil {
    private static final String cacheLoad = "resources/";
    private static Integer userId = -1;


    /**
     * 获取本地消息缓存
     *
     * @param userId 用户Id
     * @param change 前移几个星期
     *               0为默认，当前星期；
     *               1为前一个星期
     * @return List<Message>
     */
    public static List<Message> read(int userId, int change) {
        CacheUtil.userId = userId;
        String cache = getTxt(generateName(change));
        List<Message> messages = new ArrayList<>();
        if (!cache.equals("")) {
            messages = JSON.parseArray(cache, Message.class);
        }
        return messages;
    }

    public static List<Message> read(int userId) {
        return read(userId, 0);
    }

    /**
     * 获取某个联系人的消息缓存
     *
     * @param userId  用户自己的id
     * @param otherId 联系人的id
     * @param change  前几个星期，默认为0
     * @return List<Message>
     */
    public static List<Message> getMessagesOfOther(int userId, int otherId, int change) {
        List<Message> messages = read(userId, change);
        List<Message> ans = new ArrayList<>();
        //自己对自己的对话
        if (userId == otherId) {
            for (Message msg : messages) {
                if (msg == null) {
                    continue;
                }
                if (msg.getSender() == userId && msg.getReceiver() == userId) {
                    ans.add(msg);
                }
            }
            return ans;
        }

        //用户自己与他人的对话
        for (Message msg : messages) {
            if (msg == null) {
                continue;
            }
            if (msg.getReceiver() == otherId || msg.getSender() == otherId) {
                ans.add(msg);
            }
        }
        return ans;
    }

    public static List<Message> getMessagesOfOther(int userId, int otherId) {
        return getMessagesOfOther(userId, otherId, 0);
    }

    //写入缓存
    public static boolean write(int userId, Message message) {
        CacheUtil.userId = userId;
        if (message == null || message.getReceiver() == 0 || message.getSender() == 0) {
            return false;
        }

        //根据时间生成缓存名称
        String name = generateName();

        //获取缓存
        String cache = getTxt(name);
        List<Message> messages = new ArrayList<>();
        if (!cache.equals("")) {
            messages = JSON.parseArray(cache, Message.class);
        }
        messages.add(message);
        writeTxt(MyUtils.toJson(messages, 2), name);
        return true;
    }

    //根据当前时间生成名称，user2-2020-15.sav,15为一年中的第几个星期
    public static String generateName(int change) {
        String name = "";
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int week = now.get(Calendar.WEEK_OF_YEAR) - change;

        name += "user" + CacheUtil.userId + "-" + year + "-" + week + ".sav";
        return name;
    }

    public static String generateName() {
        return generateName(0);
    }

    //添加联系人
    public static void writeOtherId(Integer userId, Integer otherId) {
        String fileName = "the_contacts_of_user_" + userId + ".sav";
        List<Integer> otherIds = readOtherId(userId);
        if (!otherIds.contains(otherId)) {
            otherIds.add(otherId);
        }
        writeTxt(MyUtils.toJson(otherIds), fileName);
    }

    //删除联系人
    public static void deleteOtherId(Integer userId, Integer otherId) {
        String fileName = "the_contacts_of_user_" + userId + ".sav";
        List<Integer> otherIds = readOtherId(userId);
        otherIds.remove(otherId);
        writeTxt(MyUtils.toJson(otherIds), fileName);
    }

    /**
     * 获取user的联系人列表
     *
     * @param userId 用户自己的id
     * @return List<Integer>
     */
    public static List<Integer> readOtherId(Integer userId) {
        String fileName = "the_contacts_of_user_" + userId + ".sav";
        String cache = getTxt(fileName);
        List<Integer> otherIds = new ArrayList<>();
        if (!cache.equals("")) {
            otherIds = MyUtils.getIntArray(cache);
        }
        return otherIds;
    }

    //删除前几个星期之前的缓存
    public static void deleteCache(int userId, int change) {
        CacheUtil.userId = userId;
        int week = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);

        for (int i = change; i <= week; i++) {
            String cacheName = generateName(i);
            FileUtil.deleteFile(cacheLoad + cacheName);
        }
    }


    private static String getTxt(String filePath) {
        BufferedReader reader = null;
        File file = new File(cacheLoad + filePath);
        try {
            if (file.exists()) {
                reader = new BufferedReader(
                        new InputStreamReader(
                                new FileInputStream(file), "UTF-8"
                        ));

                String ans = "";
                String getLine;
                while ((getLine = reader.readLine()) != null) {
                    ans += getLine;
                }
                return ans;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    private static void writeTxt(String str, String filePath) {
        FileOutputStream writer = null;
        File file = new File(cacheLoad + filePath);

        try {
            writer = new FileOutputStream(file);
            writer.write(str.getBytes("UTF-8"));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
